package com.lmabbe.common.datasources.handle;

import com.lmabbe.common.datasources.mapper.InitResourceMapper;
import com.lmabbe.common.datasources.mapper.InitSysDictMapper;
import com.lmabbe.common.datasources.mapper.InitSysParamMapper;
import com.lmabbe.common.global.context.TenantBuildContext;
import org.springframework.context.ApplicationContext;

/**
 * 初始化应用
 *
 * @author lmabbe
 */
public abstract class InitApplicationHandle {

    /**
     * 构建租户的上下文
     *
     * @date 2022/2/19 2:33 PM
     * @author liming
     */
    protected ApplicationContext applicationContext;

    /**
     * spring的applicationContext
     *
     * @date 2022/2/19 2:33 PM
     * @author liming
     */
    protected TenantBuildContext tenantContext;

    private InitSysDictMapper initSysDictMapper;
    private InitSysParamMapper initSysParamMapper;
    private InitResourceMapper initResourceMapper;

    /**
     * 下一步操作
     */
    private InitApplicationHandle next;


    public InitApplicationHandle(ApplicationContext applicationContext, TenantBuildContext tenantContext) {
        this.applicationContext = applicationContext;
        this.tenantContext = tenantContext;
    }

    /**
     * 具体处理事项
     *
     * @param context 上下文
     * @date 2022/2/19 2:21 PM
     * @author liming
     */
    abstract void handle(InitApplicationContext context);

    /**
     * 执行器
     *
     * @param context
     */
    public void exec(InitApplicationContext context) {
        handle(context);
        if (this.next != null) {
            this.next.exec(context);
        }
    }

    public void setNext(InitApplicationHandle next) {
        this.next = next;
    }

    protected InitSysDictMapper getInitSysDictMapper() {
        if (this.initSysDictMapper == null) {
            return applicationContext.getBean(InitSysDictMapper.class);
        } else {
            return this.initSysDictMapper;
        }
    }

    protected InitSysParamMapper getInitSysParamMapper() {
        if (this.initSysParamMapper == null) {
            return applicationContext.getBean(InitSysParamMapper.class);
        } else {
            return this.initSysParamMapper;
        }
    }

    protected InitResourceMapper getInitResourceMapper() {
        if (this.initResourceMapper == null) {
            return applicationContext.getBean(InitResourceMapper.class);
        } else {
            return this.initResourceMapper;
        }
    }
}
